package com.example.demo.utils;


import com.example.demo.common.DataMapping;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;

/**
 * @author linjingze
 * @date 2023/12/18 2:16 PM
 */
public class DataMappingUtils {


    public static void setFieldValue(Object object, String fieldName, String fieldValue) {
        if (StringUtils.isBlank(fieldValue)) {
            return;
        }
        try {

            Class<?> clazz = object.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                // 检查字段上是否有注解
                if (field.isAnnotationPresent(DataMapping.class)) {
                    DataMapping fieldMapping = field.getAnnotation(DataMapping.class);
                    // 如果注解的值与传入的字段名匹配，设置该字段的值
                    if (fieldMapping.value().equals(fieldName) || fieldMapping.otherName().equals(fieldName)) {
                        field.setAccessible(true); // 使私有字段可访问
                        if (field.getType() == BigDecimal.class) {
                            field.set(object, BigDecimalUtils.toBigDecimalWithFormat(fieldValue)); // 设置字段的值
                        } else {
                            field.set(object, fieldValue); // 设置字段的值
                        }
                        break;
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("fieldName:异常" + fieldName);
        }
    }
}
